package icu.lookyousmileface.completables;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author starrysky
 * @title: CompletableUse
 * @projectName Juc_Pro
 * @description: CompletableFuture
 *  * 异步调用： CompletableFuture
 *  * // 异步执行
 *  * // 成功回调
 *  * // 失败回调
 * @date 2021/1/302:13 上午
 */
public class CompletableUse {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        //没有返回值的异步回调
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(3);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(" 异步任务执行成功！");
//        });
//        System.out.println("main主线程");
//        //获取异步执行的结果
//        completableFuture.get();

        //又返回值的异步回调
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+":supplyAsync=>ok");
            int sum = 10/0;
            return 1024;
        });
        //编译
        //编译成功
        System.out.println(completableFuture.whenComplete((u1,u2)->{
            System.out.println("t=>"+u1);//正常的返回结果
            System.out.println("u=>"+u2);//错误信息
            //编译失败
        }).exceptionally((e)->{
            e.printStackTrace();
            return 2233; //错误的返回结果
        }).get());
    }
}
